<?php 
/**
 * 文献操作
 DROP TABLE IF EXISTS `dict_document`;
CREATE TABLE `dict_document` (
  `d_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `u_id` int(10) unsigned NOT NULL,
  `docname` varchar(255) NOT NULL,
  PRIMARY KEY (`d_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 */
Class DocumentModel extends RelationModel{
  protected $_link = array(
      'Thesis' => array(
          'mapping_type'  => HAS_ONE,
          'class_name'    => 'Thesis',
          'foreign_key'   => 'd_id',
          // 'mapping_fields'=> ''
        ),
      'Item' => array(
          'mapping_type'  => HAS_MANY,
          'class_name'    => 'Item',
          'foreign_key'   => 'd_id',
          'mapping_name'  => 'items',
          'mapping_order' => 'itemname desc',
        ),
      'User' => array(
          'mapping_type'  => BELONGS_TO, 
          'class_name'    => 'User',
          'foreign_key'   => 'u_id',
          'as_fields'     => 'username',
        ),
    );

  /**
   * 获得一个用户的所有文档，包括见解
   * @param  int    $u_id [description]
   * @return [type]       [description]
   */
  public function selectAllDocAndThesisByUid(int $u_id)
  {
    return $this->where('u_id=' . $u_id)->relation("thesis")->select();
  }

  /**
   * 获得一个用户的所有文档
   * @param  int    $u_id [description]
   * @return [type]       [description]
   */
  public function selectAllDocByUid(int $u_id)
  {
    return $this->where('u_id=' . $u_id)->select();
  }

  /**
   * 添加一个文档
   * @param [type] $data [description]
   */
  public function addDoc($data)
  {
    return $this->add($data);
  }

  /**
   * 更新一个文档的信息
   * @param  [type] $data [description]
   * @return [type]       [description]
   */
  public function updateDoc($data)
  {
    return $this->save($data);
  }

  /**
   * 删除某一个文档，以及文档相关的见解、词条、例子
   * @param  int    $d_id [description]
   * @return [type]       [description]
   */
  public function delDocByDid(int $d_id)
  {

    if(D('Circle')->selectCircleByCid($d_id))
      return false;
    else {
      // 先删除词条和例子，再删除见解和文献
      D("Example")->delExampleByDid($d_id);
      D('Item')->delItemByDid($d_id);
      return $this->where('d_id = ' . $d_id)->delete();
    } 
  }

  
}
 ?>